import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class RecordExpenseDialog extends JDialog {
    private JTextField dateField;
    private JTextField amountField;
    private JTextField categoryField;
    private JTextField remarksField;
    private JLabel budgetLabel;
    private Map<String, Integer> budgets;

    public RecordExpenseDialog(JFrame owner) {
        super(owner, "记录支出", true);
        setSize(400, 300);
        setLocationRelativeTo(owner); // 居中显示
        setLayout(new GridLayout(6, 1, 9, 9));

        // 创建输入字段
        dateField = new JTextField();
        amountField = new JTextField();
        categoryField = new JTextField();
        remarksField = new JTextField();
        budgetLabel = new JLabel("本月剩余预算: 1000 元");

        // 加载已有预算
        budgets = loadBudgets();

        // 添加标签和输入字段
        add(new JLabel("日期 (yyyy-MM-dd):"));
        add(dateField);
        add(new JLabel("金额:"));
        add(amountField);
        add(new JLabel("类别:"));
        add(categoryField);
        add(new JLabel("备注:"));
        add(remarksField);
        add(budgetLabel);

        // 监听日期字段的变化
        dateField.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                // 不需要处理
            }

            @Override
            public void focusLost(FocusEvent e) {
                String dateStr = dateField.getText().trim();
                if (validateDate(dateStr)) {
                    int remainingBudget = calculateRemainingBudget(dateStr);
                    budgetLabel.setText("本月剩余预算: " + remainingBudget + " 元");
                } else {
                    budgetLabel.setText("请输入有效的日期格式 (yyyy-MM-dd)。");
                }
            }
        });

        // 创建保存按钮
        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String dateStr = dateField.getText().trim();
                String amountStr = amountField.getText().trim();
                String category = categoryField.getText().trim();
                String remarks = remarksField.getText().trim();

                // 收集所有错误信息
                StringBuilder errorMessages = new StringBuilder();

                if (!validateDate(dateStr)) {
                    errorMessages.append("请输入有效的日期格式 (yyyy-MM-dd)。\n");
                }

                if (!validateAmount(amountStr)) {
                    errorMessages.append("金额必须为正数。\n");
                }

                int remainingBudget = Integer.parseInt(budgetLabel.getText().split(": ")[1].split(" ")[0]);
                double amount = Double.parseDouble(amountStr);
                if (amount > remainingBudget) {
                    errorMessages.append("本月支出超额。\n");
                }

                // 如果有错误信息，则显示并返回
                if (errorMessages.length() > 0) {
                    JOptionPane.showMessageDialog(RecordExpenseDialog.this, errorMessages.toString(), "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 保存记录
                saveExpenseRecord(dateStr, amountStr, category, remarks);
                JOptionPane.showMessageDialog(RecordExpenseDialog.this, "支出记录已保存。");
                dispose(); // 关闭对话框
            }
        });

        // 添加保存按钮
        add(saveButton);
    }

    private boolean validateDate(String dateStr) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        try {
            Date date = dateFormat.parse(dateStr);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    private boolean validateAmount(String amountStr) {
        try {
            double amount = Double.parseDouble(amountStr);
            return amount > 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private int calculateRemainingBudget(String dateStr) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        String monthStr = null;
        try {
            monthStr = dateFormat.format(dateFormat.parse(dateStr));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        int totalSpent = 0;
        String filePath = "Gitzuoye/src/expenses";
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 4 && monthStr.equals(parts[0].substring(0, 7))) {
                    totalSpent += Integer.parseInt(parts[1]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        int budget = 1000; // 默认预算
        if (budgets.containsKey(monthStr)) {
            budget = budgets.get(monthStr);
        }

        return budget - totalSpent;
    }

    private void saveExpenseRecord(String date, String amount, String category, String remarks) {
        String filePath = "Gitzuoye/src/expenses";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            writer.write(date + "," + amount + "," + category + "," + remarks);
            writer.newLine();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "无法保存记录，请检查文件路径或权限。", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private Map<String, Integer> loadBudgets() {
        Map<String, Integer> budgets = new HashMap<>();
        String filePath = "Gitzuoye/src/budgets";
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 2) {
                    budgets.put(parts[0], Integer.parseInt(parts[1]));
                }
            }
        } catch (IOException e) {
            // 文件不存在或读取失败，忽略
        }
        return budgets;
    }
}